package org.darcy.youchat.library.emoji;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.DisplayMetrics;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 表情库Kit
 */
public class YouChatEmotionKit {

    private static String STICKER_NAME_IN_ASSETS = "sticker";
    private static float density;
    private static float scaleDensity;
    private static String STICKER_PATH;//默认路径在 /data/data/包名/files/sticker 下
    private static YouChatEmojiImageLoader imageLoader;
    private static AssetManager assetManager;
    private static Context mContext;

    public static Context getContext() {
        return mContext;
    }

    public static void init(Context context) {
        mContext = context;
        assetManager = context.getResources().getAssets();
        String path = new File(context.getFilesDir(), STICKER_NAME_IN_ASSETS).getAbsolutePath();
        STICKER_PATH = path;
        //STICKER_PATH = "/data/data/org.darcy.youchat/files";

        copyStickerToStickerPath(STICKER_NAME_IN_ASSETS);
        StickerManager.getInstance().init();
        DisplayMetrics dm = context.getApplicationContext().getResources().getDisplayMetrics();
        density = dm.density;
        scaleDensity = dm.scaledDensity;
    }

    /**
     * 将 asset/sticker目录下默认的贴图复制到STICKER_PATH下
     */
    private static void copyStickerToStickerPath(String assetsFolderPath) {
        List<String> srcFile = new ArrayList<>();
        try {
            String[] stickers = assetManager.list(assetsFolderPath);
            for (String fileName : stickers) {
                if (!new File(YouChatEmotionKit.getStickerPath(), fileName).exists()) {
                    srcFile.add(fileName);
                }
            }
            if (srcFile.size() > 0) {
                copyToStickerPath(assetsFolderPath, srcFile);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void copyToStickerPath(final String assetsFolderPath, final List<String> srcFile) {
        new Thread(() -> {
            for (String fileName : srcFile) {
                if (fileName.contains(".")) {//文件
                    InputStream is = null;
                    FileOutputStream fos = null;
                    try {
                        is = assetManager.open(assetsFolderPath + File.separator + fileName);
                        File destinationFile;
                        if (assetsFolderPath.startsWith(STICKER_NAME_IN_ASSETS + File.separator)) {//递归回来的时候assetsFolderPath可能变为"sticker/tsj"
                            destinationFile = new File(getStickerPath(), assetsFolderPath.substring(assetsFolderPath.indexOf(File.separator) + 1) + File.separator + fileName);
                        } else {
                            destinationFile = new File(getStickerPath(), fileName);
                        }
                        fos = new FileOutputStream(destinationFile);
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = is.read(buffer)) != -1) {
                            fos.write(buffer, 0, len);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } else {
                    File dir = new File(getStickerPath(), fileName);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    copyStickerToStickerPath(assetsFolderPath + File.separator + fileName);
                }
            }
        }).start();
    }


    public static String getStickerPath() {
        return STICKER_PATH;
    }

    public static void setImageLoader(YouChatEmojiImageLoader loader) {
        imageLoader = loader;
    }

    public static YouChatEmojiImageLoader getImageLoader() {
        if (imageLoader == null) {
            throw new RuntimeException("you should use setImageLoader() in your App onCreate()");
        }
        return imageLoader;
    }


    public static int dip2px(float dipValue) {
        return (int) (dipValue * density + 0.5F);
    }

    public static int px2dip(float pxValue) {
        return (int) (pxValue / density + 0.5F);
    }

    public static int sp2px(float spValue) {
        return (int) (spValue * scaleDensity + 0.5F);
    }

    public static boolean hasExtention(String filename) {
        int dot = filename.lastIndexOf('.');
        if (dot > -1 && dot < filename.length() - 1)
            return true;
        return false;
    }
}
